package vcsn.handlers;


import java.io.File;
import java.util.Vector;

import javax.swing.JOptionPane;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;

import vcsn.ClientThread;
import vcsn.Config;
import vcsn.Configuration;
import vcsn.RelationMapBuilder;
import vcsn.Config.HeaderType;
import vcsn.Config.SyncStatus;
import vcsn.entities.PeerList;
import vcsn.entities.VectorClock;
import vcsn.utils.ExportImportHandler;

public class OnlineHandler extends AbstractHandler{

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// TODO Auto-generated method stub
		IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
	    if (window != null){
	        IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection();
	        Object firstElement = selection.getFirstElement();
	        if (firstElement instanceof IAdaptable){
	            IProject project = (IProject)((IAdaptable)firstElement).getAdapter(IProject.class);
	            Configuration configure = new Configuration(project.getLocation().toString(), project.getName());
	            try {
	            	if(Config.status == SyncStatus.OFFLINE){
	            		PeerList peerListHandler = new PeerList();
	            		Vector<String> peerList = peerListHandler.getPeerList(project.getProject().getLocation().toString() + File.separator + Config.peerFile);
	            		
	            		ClientThread client = new ClientThread();
	            		String localAddress = client.getLocalAddress(new File(project.getProject().getLocation().toString() + File.separator + Config.peerFile));
	            			            		
	            		if(peerList.size() <= 0 || peerList.size() == 1 && peerList.contains(localAddress)){
	            			Config.status = SyncStatus.ONLINE;
	            		}else{
	            			
	            			VectorClock localClock = ExportImportHandler.importVectorClock(System.getProperty(Config.homeDirectoryNotation) + File.separator + Config.localClockFile, project.getName());
	            			localClock.incrementClock(configure.getUserName() + Config.keyConnector + configure.getUserEmail());
	            			ExportImportHandler.exportVectorClock(localClock, project.getName());
	            			
	            			client.writeHeaderIntoPackageFile(project.getName(), localClock, localAddress, HeaderType.ONLINESYNCREQUEST);
	            			client.writeFileIntoPackageFile(new File(System.getProperty(Config.homeDirectoryNotation) + File.separator + Config.lastAppliedCommitHashListFile));
	            			client.flush(new File(project.getProject().getLocation().toString() + File.separator + Config.peerFile));
	            			client.disposePackage();
	            			Config.status = SyncStatus.SYNC;
	            		}
	            	}else{
	            		Config.status = SyncStatus.OFFLINE;
	            	}
	            	JOptionPane.showMessageDialog(null, Config.onlineStatusMsg + Config.status.toString(), Config.onlineDialogTitle, JOptionPane.INFORMATION_MESSAGE);
				} catch (Exception e) {
					e.printStackTrace();
				}
	        }else{ 
	        	window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
	    		MessageDialog.openInformation(window.getShell(), "Error", "No project is selected!Please select a project.");
	    		return null;
		    }
	    }else{
	    	window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    		MessageDialog.openInformation(window.getShell(), "Error", "Window is null!");
	    }
	    return null;
	}

}
